<?php
/**
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

//$c = curl_init();
//curl_setopt($c, CURLOPT_URL, 'http://www.facebook.com/login.php');
//curl_setopt($c, CURLOPT_POST, true);
//curl_setopt($c, CURLOPT_POSTFIELDS, 'email=kaku32@hotmail.com&pass=Kaku7592');
//curl_exec ($c);
//curl_close ($c); 

require 'FBsdk/src/facebook.php';


function GetFacebookMedia( $GET )
{
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '250527955081918',
  'secret' => '8b4a436bc902681ded48cbf5eeffe760',
));
// Get User ID
$facebook->setAccessToken($GET['Access_token']);
$user = $facebook->getUser();

//echo "<test>".$user."</test>";
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user)
{
  $logoutUrl = $facebook->getLogoutUrl();
  	if ($GET['Reset']=='true')
	{
		$posts_home = idx($facebook->api('/me/home?limit='.$GET['limit'].''), 'data', array());
		$posts_feed = idx($facebook->api('/me/feed?limit='.$GET['limit'].''), 'data', array());
		
		for( $i = 0 ; $i < $GET['limit'] ; $i++ ) {
			
			if ((isset($posts_home[$i]))&&(isset($posts_feed[$i]))) {
				if (strtotime($posts_home[$i]['created_time'])>strtotime($posts_feed[$i]['created_time']))
					$posts[] = $posts_home[$i];
				else
					$posts[] = $posts_feed[$i];
			}
			else if (isset($posts_home[$i]))
				$posts[] = $posts_home[$i];
			else if (isset($posts_feed[$i]))
				$posts[] = $posts_feed[$i];
		}
		
		if( isset($posts->error) )
		{
			return Array();
		}
		$_SESSION['Since'] = strtotime($posts[0]['created_time']);
		$_SESSION['Until'] = strtotime($posts[count($posts)-1]['created_time'])-1;
	}
	else
	{
		//Search New data.
		
		$posts_home = idx($facebook->api('/me/home?limit='.$GET['limit'].'&since='.$_SESSION['Since'].''), 'data', array());
		$posts_feed = idx($facebook->api('/me/feed?limit='.$GET['limit'].'&since='.$_SESSION['Since'].''), 'data', array());
		for( $i = 0 ; $i < $GET['limit'] ; $i++ ) {
				
			if ((isset($posts_home[$i]))&&(isset($posts_feed[$i]))) {
				
				if (strtotime($posts_home[$i]['created_time'])>strtotime($posts_feed[$i]['created_time']))
					$posts[] = $posts_home[$i];
				else
					$posts[] = $posts_feed[$i];
			}
			else if (isset($posts_home[$i]))
				$posts[] = $posts_home[$i];
			else if (isset($posts_feed[$i]))
				$posts[] = $posts_feed[$i];
		}
		
		if (empty($posts))
			$posts = $posts_home;
		
		$count_second = $GET['limit'] - count($posts);
		
		//Search Old data.
		$posts_home_Old = idx($facebook->api('/me/home?limit='.$count_second.'&until='.$_SESSION['Until'].''), 'data', array());
		$posts_feed_Old = idx($facebook->api('/me/feed?limit='.$count_second.'&until='.$_SESSION['Until'].''), 'data', array());
		for( $i = 0 ; $i < $count_second ; $i++ ) {
				
			if ((isset($posts_home_Old[$i]))&&(isset($posts_feed_Old[$i]))) {
				
				if (strtotime($posts_home_Old[$i]['created_time'])>strtotime($posts_feed_Old[$i]['created_time']))
					$posts_second[] = $posts_home_Old[$i];
				else
					$posts_second[] = $posts_feed_Old[$i];
			}
			else if (isset($posts_home_Old[$i]))
				$posts_second[] = $posts_home_Old[$i];
			else if (isset($posts_feed_Old[$i]))
				$posts_second[] = $posts_feed_Old[$i];
		}
		
		if (empty($posts_second))
			$posts_second = $posts_home_Old;
		
		if (!empty($posts))
			$_SESSION['Since'] = strtotime($posts[0]['created_time']);
	}
  //$posts = idx($facebook->api('/me/posts?limit='.$GET['limit'].''), 'data', array());
  //$posts = idx($facebook->api('/me/posts?limit=20'), 'data', array());
}
else
{
  $loginUrl = $facebook->getLoginUrl(  );
  //$loginUrl = "http://Fbespoke-app.com/FBeSpokeAPI/FbeStream.php&state=3013ec532f1187b4b22fdb8c38304f96";
  //<a href="https://www.facebook.com/dialog/oauth?client_id=384457058286773&amp;redirect_uri=http%3A%2F%2Fbespoke-app.com%2FbeSpokeAPI%2FFacebook%2F&amp;state=ca91952668891d64d6cf490f6a7ad5ed">Login with Facebook</a>
  
// Connect to SQL Server to Get UserAccount
//require_once 'mysql_connect.php';

//$strCommand = "SELECT * FROM Organization WHERE idOrganization = 0";
//$result = mysql_query($strSqlCommand);
//$rowAccount = @mysql_fetch_array($result);	
}

// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');

$MediaList = array();

if ($user)
{
	foreach ($posts as $post)
	{
		array_push ($MediaList, MakeMediaArray_Facebook($post,$user_profile,$facebook));
	}
	if(!empty($posts_second))
	{
		$_SESSION['Until'] = strtotime($posts_second[count($posts_second)-1]['created_time'])-1;
//		foreach ($posts_second as $post)
		for ($i=0 ; $i < count($posts_second); $i++)
		{
			array_push ($MediaList, MakeMediaArray_Facebook($posts_second[ $i ],$user_profile,$facebook));
		}
	}
}
else
{
//	echo '<a href="'.$loginUrl.'">'.$loginUrl.'</a>';
	header('Location: '. $loginUrl );
}
return $MediaList;
}// End of Function

	function idx(array $array, $key, $default = null) {
		return array_key_exists($key, $array) ? $array[$key] : $default;
	}
	
function MakeMediaArray_Facebook ($post,$user_profile,$facebook)
{
	$Media = array();
	if( $strSubID = strstr( $post['id'], "_" ) )
		$BeMediaID = substr($strSubID,1);
	else
		$BeMediaID = $post['id'];
		
	if( isset($post['from']['name']))
		$Author = $post['from']['name'];
	else
		$Author = "";
		
	if(isset($post['link']))
		$strLink = $post['link'];
	else if (isset($post['actions']))
		$strLink = $post['actions'][0]['link'];
	else
		$strLink = 'https://www.facebook.com/'.$user_profile['username'].'/home/'.$BeMediaID;
	
	//Text Title
	if( isset($post['story']) )
		$strTitle = $post['story'];
	else if ((isset($post['caption']))&&(!isset($post['message'])))
		$strTitle = $post['caption'];
	else if (isset($post['name']))
		$strTitle = $post['name'];
	else if ((isset($post['application']['name']))&&($post['application']['name']=='Instagram'))
		$strTitle = "Instagram Application";
	else
		$strTitle = "";
	
	//Text Description
	if( isset($post['message']))
		$strMessage = $post['message'];
	else if( isset($post['description']))
		$strMessage = $post['description'];
	else
		$strMessage = "";
		
	if((strlen($strTitle)>0)||(strlen($strMessage)>0)||(isset($post['object_id'])))
	{
		$MediaDetial = array( "Head"=>"Media", "ID"=>"", "BeMediaID"=>"Facebook_".$BeMediaID, "MediaType"=>$post['type'], "CommentCount"=>$post['comments']['count'], "WebLink"=>$strLink, "Source"=>"Facebook", "Author"=>$Author,"lastUpdate"=>strtotime($post['updated_time']));
		array_push( $Media, $MediaDetial );
	}
	
	if((strlen($strTitle)>0)||(strlen($strMessage)>0))
	{
		$MediaDetial = array( "Head"=>"Text", "ID"=>"", "Title"=>$strTitle, "Description"=>$strMessage);
		array_push( $Media, $MediaDetial );
	}
	
	if(isset($post['object_id'])) {
	
		$graphURL = 'https://graph.facebook.com/'.$post['object_id'].'?accesstoken='.$facebook->getAccessToken();
		$graph = json_decode(get_curl_2($graphURL),true);
		if (($graph)&&(!isset($graph['error']))) {
			$Width = $graph['width'];
			$Height = $graph['height'];
			$FilePath = $graph['source'];
		
			$MediaDetial = array( "Head"=>"Image_W_H", "ID"=>"", "Type"=>'URL', "Width"=>$Width, "Height"=>$Height, "FileName"=>XMLCharEncode($FilePath), "Description"=>$strMessage);
			array_push( $Media, $MediaDetial );
		}		
		else if ( isset($post['picture']) ) {
		//if( isset(strstr( XMLCharEncode($post['picture']), "_n." )))
			$picture_n = str_replace("_s.","_n.",XMLCharEncode($post['picture']));
			$MediaDetial = array( "Head"=>"Image", "ID"=>"", "Type"=>'URL', "FileName"=>XMLCharEncode($picture_n), "Description"=>$strMessage);
			array_push( $Media, $MediaDetial );
		}
	}
	
	/**if( isset($post['picture']) )
	{
		
		//if( isset(strstr( XMLCharEncode($post['picture']), "_n." )))
		$picture_n = str_replace("_s.","_n.",XMLCharEncode($post['picture']));
		$MediaDetial = array( "Head"=>"Image", "ID"=>"", "Type"=>'URL', "FileName"=>XMLCharEncode($picture_n), "Description"=>$strMessage);
		array_push( $Media, $MediaDetial );
	}**/
	return $Media;
}

function get_curl_2($url){
    if(function_exists('curl_init')){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); 
        $output = curl_exec($ch);
        echo curl_error($ch);
        curl_close($ch);
        return $output;
    }else{
        return file_get_contents($url);
    }
}
?>
